//
//  TechDetailViewController.m
//  LPSNews
//
//  Created by Ruan on 14-10-18.
//  Copyright (c) 2014年 LPS. All rights reserved.
//

#import "DigitalDetailViewController.h"
#import "UIButton+NavButton.h"
#import "AFNetworking.h"
#import "DetailMode.h"
#import "DetailView.h"
#import "SDWebImageManager.h"
#import "NSString+MD5.h"
#import "FilePathManager.h"
#import "DB_Collect.h"

#define tDString @"http://c.m.163.com/nc/article/"

@interface DigitalDetailViewController () <UIWebViewDelegate>

@property (nonatomic, retain) DetailView *techDetailView;
@property (nonatomic, retain) UIScrollView *scrollview;
@property (nonatomic, retain) UIImageView *backImageView;
@property (nonatomic, retain) UIActivityIndicatorView *activityView;
@property (nonatomic, retain) DetailMode *techDetail;
@property (nonatomic, retain)  NSMutableArray *imageURLMD5Array;
@property (nonatomic, retain) DB_Collect *db;
@property (nonatomic, retain)  NSMutableArray *imagePathStringMD5Array;
@property (nonatomic, retain) UIButton *rightButton;
@property (nonatomic, retain)  NSString *htmlPathString;
@property (nonatomic, retain) NSString *techDetailString;
@property (nonatomic, retain)  SDWebImageManager *sdmanager;
@property (nonatomic, retain) AFHTTPRequestOperationManager *manager;
@end

@implementation DigitalDetailViewController

- (void)dealloc
{
    //**** 退出取消网络请求,不然请求回来后,contrllor已经销毁,就崩溃
    [self.techDetailView stopLoading];
    [self.manager.operationQueue cancelAllOperations];
    [self.sdmanager cancelAll];
    
    [_rightButton release];
    [_db release];
    [_imageURLMD5Array release];
    [_imagePathStringMD5Array release];
    [_activityView  release];
    [_backImageView release];
    [_scrollview release];
    [_techDetailView release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 2. 添加左侧返回按钮
    UIButton *leftButton = [UIButton addNavButtonWithNormalImageString:@"back" andHeightLightedImageString:@"back_highlighted"];
    CGSize leftButtonSzie = leftButton.currentImage.size;
    leftButton.frame = (CGRect){CGPointZero,leftButtonSzie};
    leftButton.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarButton = [[[UIBarButtonItem alloc] initWithCustomView:leftButton] autorelease];
    self.navigationItem.leftBarButtonItem = leftBarButton;

    // 3. 添加右侧收藏按钮
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:@"icon_star"] forState:UIControlStateNormal];
    [rightButton setImage:[UIImage imageNamed:@"icon_star_full"] forState:UIControlStateSelected];
    rightButton.selected = NO;
    CGSize rightButtonSzie = rightButton.currentImage.size;
    rightButton.frame = (CGRect){CGPointZero,rightButtonSzie};
    [rightButton addTarget:self action:@selector(collectClick:) forControlEvents:UIControlEventTouchUpInside];
    self.rightButton = rightButton;
    UIBarButtonItem * rightBarButton = [[[UIBarButtonItem alloc] initWithCustomView:rightButton] autorelease] ;
    self.navigationItem.rightBarButtonItem = rightBarButton;

    // 5. 添加背景logo的图片
    UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"updatabackgroudImage"]];
    backImageView.frame = self.view.bounds;
    self.backImageView = backImageView;
    
    // 6. 添加链接中的菊花
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.frame = CGRectMake(0, 0, 80, 80);
    activityView.center = CGPointMake(160, 170);
    activityView.backgroundColor = [UIColor lightGrayColor];
    activityView.alpha = 0.8;
    activityView.layer.cornerRadius = 5;
    activityView.layer.masksToBounds = YES;
    self.activityView = activityView;
    [activityView startAnimating];

    
    // 7. 创建scrollview 用于滚动webView
    UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollview = scrollview;
    
    // 8. 创建自定义的webview 显示网页内容
    DetailView *techDetailView = [[DetailView alloc] initWithFrame:self.view.frame];
    techDetailView.delegate =self;
    self.techDetailView = techDetailView;
    
    
    [self.view addSubview:scrollview];
    [scrollview addSubview:techDetailView];
    [backImageView addSubview:activityView];
    [self.view addSubview:backImageView];
    [self.view bringSubviewToFront:backImageView];
    
    [backImageView release];
    [activityView release];
    [techDetailView release];
    [scrollview release];

    
    // 9. 拼接链接字符串
    NSString *str = tDString;
    NSString *techDetailString = [str stringByAppendingFormat:@"%@/full.html",self.docid];
    self.techDetailString = techDetailString;
    // 10.调用谅解数据的方法
    [self downloadDetailDataWithURLString:techDetailString];
    
    
}


/**
 *  下载数据方法
 */

- (void)downloadDetailDataWithURLString:(NSString *)urlString
{
    // 1. 开启状态栏的联网状态
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSString *techDetailURLString = urlString;
    
    // 2.发送网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    self.manager = manager;
    
    [manager GET:techDetailURLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 3. 接收数据
        NSDictionary *dict = responseObject;
        NSArray *keyArray = [dict allKeys];
        NSString *keyStr = [keyArray lastObject];
        NSDictionary *techdict = [dict objectForKey:keyStr];
        // 1. 打开数据库
        DB_Collect *db = [[DB_Collect alloc] init];
        self.db = db;
        // 4. 数据转模型
        DetailMode *techDetail = [[DetailMode alloc] init];
        [techDetail setValuesForKeysWithDictionary:techdict];
        self.techDetail = techDetail;
        techDetail.imagecount = (int)techDetail.img.count;
        // 5. 创建可变字符串,用于修改body中的图片占位符
        NSMutableString *newBodyStr = [techDetail.body mutableCopy];
        
        // 6.创建可变数组,存放多个图片的网址,遍历图片数组,存放在此字符串
        NSMutableArray *imageURLArray = [[NSMutableArray alloc] init];
        for (NSDictionary *tempDict in techDetail.img)
        {
            NSString *imagesrc = tempDict[@"src"];
            [imageURLArray addObject:imagesrc];
        }
        
        
        // 7.imageURLArray判断数组 是否为空,如果为空不用显示图片.
        if (imageURLArray.count == 0) {
            
            // 8.将body转为HTML文件,存放在webcache路径中,方便webView显示
            NSString *htmlPathString = [FilePathManager bodyPathCache:techDetail.title];
            self.htmlPathString = htmlPathString;
            [techDetail.body writeToFile:htmlPathString atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
            // 9.设置webview里的 标题 和 时间 Label
            self.techDetailView.detailTitle.text = techDetail.title;
            CGRect techDetailTitleFrame = [self.techDetailView.detailTitle.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 10, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil];
            
            self.techDetailView.detailTitle.frame = CGRectMake(0, -40, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(techDetailTitleFrame));
            self.techDetailView.ptimeLabel.text = techDetail.ptime;
            self.techDetailView.ptimeLabel.frame = CGRectMake(0, CGRectGetMaxY(self.techDetailView.detailTitle.frame) +5, [UIScreen mainScreen].bounds.size.width , 10);
            
            // 10. webview显示存放的HTML文件
                            NSError *error = nil;
                NSString *html = [[NSString alloc] initWithContentsOfFile:
                                  htmlPathString encoding: NSUTF8StringEncoding error:&error];
                
                [self.techDetailView loadHTMLString:html baseURL:[NSURL URLWithString:htmlPathString]];
                
                [html release];
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                
           
            // 4. 判断数据库中是否有 docid 此ID值 ,如果用右侧收藏按钮为选中状态
            if ([self.db collectDataisExistsDocid:self.docid]) {
                self.rightButton.selected = YES;
            }
            
            [self.activityView stopAnimating];
            [self.backImageView removeFromSuperview];
            [self.activityView removeFromSuperview];
            
            
        }else
        {
            // 有图片,将图片的URL地址加入到Body 用WebView显示
            NSLog(@"有图片   %d",(int)imageURLArray.count);
            
            
            //1. 存imageURL转为MD5码的数据
            NSMutableArray *imageURLMD5Array = [[NSMutableArray alloc] init];
            self.imageURLMD5Array = imageURLMD5Array;
            
            // 2. 可变数组用于存保存到本地图片的路径
            NSMutableArray *imagePathStringMD5Array = [[NSMutableArray alloc] init];
            self.imagePathStringMD5Array = imagePathStringMD5Array;

            // 3. 循环图片的数量,分别存储image到本地
            for (int i = 0; i < imageURLArray.count ; i ++) {
                
                NSString *urlstr = imageURLArray[i];
                
                
                // 4.用SDWebImageManager方法 下载图片到本地
                SDWebImageManager *sdmanager = [SDWebImageManager sharedManager];
                self.sdmanager = sdmanager;
                
                [sdmanager downloadImageWithURL:[NSURL URLWithString:urlstr] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {

                } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                    
                    NSLog(@"下载成功%d",i);
                
                    // 5.将图片转为data
                    NSData *data = UIImageJPEGRepresentation(image, 1);

                    // 6.图片的URL地址转为MD5保存图片
                    NSString *imageURLMD5 = [[[techDetail.docid stringByAppendingFormat:@"%d",i] MD5] stringByAppendingString:@".jpg"];
                    [imageURLMD5Array addObject:imageURLMD5];
                    
                    // 7.imagePathStringMD5 图片的保存路径缓存文件夹webcache
                    NSString *imagePathStringMD5 = [FilePathManager imagePathCache:imageURLMD5];
   
                    // 8.将图片写入缓存磁盘
                    [data writeToFile:imagePathStringMD5 atomically:YES];
                    
                    // 9.保存图片的绝对路径到数组,用于收藏时copy到collect文件
                    [imagePathStringMD5Array addObject:imagePathStringMD5];
                    
                    // 10.创建要插入body的HTML语句,将imagePathStringMD5 的绝对路径插入
                     NSMutableString *htmlstr = [[NSMutableString alloc] initWithString:@"<img src=\"\" onload=\"javascript:if(this.width>320){this.width=295;this.height=this.height*295/this.width;}\">"];
                     [htmlstr insertString:imagePathStringMD5 atIndex:10];
                    
                    // 11. 插入htmlstr html语句到body
                     NSString *tempStr = [NSString stringWithFormat:@"<!--IMG#%d-->",i];
                     NSRange range = [newBodyStr  rangeOfString:tempStr];
                     [newBodyStr insertString:htmlstr atIndex:range.location];
                    
                    // 12.当为最后一个图片时,webview开始加载数据
                    if ((i + 1) == imageURLArray.count ) {

                        // 13.方法和无图片的加载方式相同
                        NSString *htmlPathString = [FilePathManager bodyPathCache:techDetail.title];
                        self.htmlPathString = htmlPathString;
                        [newBodyStr writeToFile:htmlPathString atomically:YES encoding:NSUTF8StringEncoding error:nil];

                         self.techDetailView.detailTitle.text = techDetail.title;

                         CGRect techDetailTitleFrame = [self.techDetailView.detailTitle.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 10, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil];

                         self.techDetailView.detailTitle.frame = CGRectMake(0, -40, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(techDetailTitleFrame));

                         self.techDetailView.ptimeLabel.text = techDetail.ptime;
                         self.techDetailView.ptimeLabel.frame = CGRectMake(0, CGRectGetMaxY(self.techDetailView.detailTitle.frame) +5, [UIScreen mainScreen].bounds.size.width , 10);

                            NSError *error = nil;
                            NSString *html = [[NSString alloc] initWithContentsOfFile:
                                              htmlPathString encoding: NSUTF8StringEncoding error:&error];
                            
                            [self.techDetailView loadHTMLString:html baseURL:[NSURL URLWithString:htmlPathString]];

                            [html release];
                        
                        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                        
                        // 4. 判断数据库中是否有 docid 此ID值 ,如果用右侧收藏按钮为选中状态
                        if ([self.db collectDataisExistsDocid:self.docid]) {
                            self.rightButton.selected = YES;
                        }
                        
                        [self.activityView stopAnimating];
                        [self.activityView removeFromSuperview];
                        [self.backImageView removeFromSuperview];
                    }

                    [htmlstr release];
                  
                }];
            
            }
        [imageURLMD5Array release];
        [imagePathStringMD5Array release];
    }
        [imageURLArray release];
        [newBodyStr release];
        [techDetail release];
        [db release];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

/**
 *  webview加载完毕后改变其显示属性
 *
 *
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 1. 改变字体为原文档字体大小的85%
    [self.techDetailView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='85%'"];
    
    // 2. 计算文本的高度
    NSString *height_str= [self.techDetailView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    CGFloat height = [height_str floatValue];
    
    // 3.设置webview的显示frame
    self.techDetailView.frame =  CGRectMake(5, 50, [UIScreen mainScreen].bounds.size.width-5, height+50);
    // 4.设置webview滚动的范围
    self.techDetailView.scrollView.contentSize =  CGSizeMake(self.techDetailView.frame.size.width, height + 50);
    
    // 设置scrollview 的contentSize
    self.scrollview.contentSize = self.techDetailView.scrollView.contentSize;
    self.scrollview.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);

     [webView stopLoading];
   
}

/**  back 出栈
 *  点击返回键要判断webcache文件数量是否大于50 大于50清空文件夹
 *
 *   */
- (void)backClick:(UIButton *)btn
{
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSArray *listFileArray = [fm subpathsAtPath:[FilePathManager webCachePath]];
    
   
    if (listFileArray.count >= 50) {
        
        for (NSString *fileStr in listFileArray) {

            [fm removeItemAtPath:[FilePathManager imagePathCache:fileStr] error:nil];
        }
    }
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}
/**
 * 1. 将文本信息保存到数据库
 * 2.  将图片的信息保存到collector文件夹
 *
 */
- (void)collectClick:(UIButton *)btn
{
    
    //判断是否下载数据完毕 ,判断logo的图片是否已经移除
    
    if (!self.backImageView.superview) {

        // 1.设置Lable实现 收藏成功 和取消收藏
        UILabel *textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 120, 80);
        textLable.center = CGPointMake([UIScreen mainScreen].bounds.size.width * 0.5, [UIScreen mainScreen].bounds.size.height * 0.5);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view addSubview:textLable];
        textLable.alpha = 0;
        
        
        // 2. 判断按钮是否被选中.没有选中就没有收藏
        if (!btn.selected) {
         
            // 3.判断模型内的图片数量是否为0,不为0,则需要保存图片
            if (self.techDetail.imagecount != 0) {
                
                // 4.用收藏模型保存数据,
                NSMutableString *collectbody = [self.techDetail.body mutableCopy];
                
                // 5. 将缓存webcache 中文件copy到collector 文件中
                for (int i = 0 ; i < self.techDetail.imagecount; i++) {
                    
                    NSString *collectPath = [[FilePathManager collectorFolderPath] stringByAppendingPathComponent:self.imageURLMD5Array[i]];
                    
                    NSFileManager *manager = [NSFileManager defaultManager];
                    
                    // 6.将webcache文件中的图片copy到collector 文件中
                    if (![manager isExecutableFileAtPath:collectPath]) {
                        [manager copyItemAtPath:self.imagePathStringMD5Array[i] toPath:collectPath error:nil];
                    }
                    
                    NSMutableString *collecthtmlstr = [[NSMutableString alloc] initWithString:@"<img src=\"\" onload=\"javascript:if(this.width>320){this.width=295;this.height=this.height*295/this.width;}\">"];
                    [collecthtmlstr insertString:self.imageURLMD5Array[i] atIndex:10];
                    
                    
                    NSString *tempStr = [NSString stringWithFormat:@"<!--IMG#%d-->",i];
                    NSRange range = [collectbody  rangeOfString:tempStr];
                    [collectbody insertString:collecthtmlstr atIndex:range.location];
                    [collecthtmlstr release];
                }
                
                // 将信息写入到数据库
              [self.db insertCollectDataWithDocid:self.techDetail.docid Title:self.techDetail.title Ptime:self.techDetail.ptime Body:collectbody Imagecount:@(self.techDetail.imagecount)];
                [collectbody release];
                
            }else
            {// 没有图片直接保存文本信息
                
            [self.db insertCollectDataWithDocid:self.techDetail.docid Title:self.techDetail.title Ptime:self.techDetail.ptime Body:self.techDetail.body Imagecount:@(self.techDetail.imagecount)];
            }
            
            textLable.text = @"收藏成功";
            [UIView animateWithDuration:0.1 animations:^{
                [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0.8;
                } completion:^(BOOL finished) {
                    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
                        textLable.alpha = 0;
                    } completion:^(BOOL finished) {
                        [textLable removeFromSuperview];
                    }];
                }];
            }];
            
            btn.selected = YES;
        }else   // 如果收藏的button被选中,点击button删除收藏
        {
            CollectDataMode *collectData = [self.db selectCollectDataWithDocid:self.techDetail.docid];
            
            // 1.查询数据库,将docid转为MD5,判断数据库的imagecount是否为0
            // 不为0则需要删除collector文件夹内的图片
            //   2.查询数据库,将docid转为MD5,找到图片的路径并删除图片
            if (collectData.imagecount  != 0) {
                for (int i = 0; i < collectData.imagecount; i++) {
                    NSString *imageMD5 = [[[self.docid stringByAppendingFormat:@"%d",i] MD5] stringByAppendingString:@".jpg"];
                    NSLog(@"imageMD5 = %@",imageMD5);
                    [FilePathManager deleteCollectFileWithPath:imageMD5];
                }
            }
            //3.删除数据内的文本信息
            [self.db deleteCollectDataWithDocid:self.techDetail.docid];
            
            textLable.text = @"取消收藏";
            [UIView animateWithDuration:0.1 animations:^{
                [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0.8;
                } completion:^(BOOL finished) {
                    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
                        textLable.alpha = 0;
                    } completion:^(BOOL finished) {
                        [textLable removeFromSuperview];
                    }];
                }];
            }];
            btn.selected = NO;
        }
        [textLable release];
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}


@end
